import React, {Component} from 'react';
import axios from 'axios';
import './App.css';
import Table from 'antd/lib/table';
import {HashRouter as Router, Link, Route, Switch} from 'react-router-dom'

import {Layout, Breadcrumb, Icon, Menu, Dropdown} from 'antd';

const {Header, Content, Footer, Sider} = Layout;
const SubMenu = Menu.SubMenu;


const table_header = {
    'user':{
        'username':{
            render: (username, record) => (<Link to={`/users/${record.id}`}> {username}</Link>)
        }
    }
}

class BaseList extends Component {
    constructor(props) {
        super(props)
        this.state = {
            pagination: {},
            loading: true,
            items: [],
        };

    }

    componentDidMount() {
        axios.get(this.props.api).then(res => {
            this.setState({
                items: res.data,
                loading: false
            })
        })
    }

    render() {
        return (
            <div>
                <Table dataSource={this.state.items} columns={this.props.columns} rowKey={record => record.registered}
                       loading={this.state.loading}/>
            </div>
        )
    }
}


const UserSubLayout = () =>
    <Switch>
        <Route path="/users" exact component={UserList}/>
        <Route path="/users/:userId" component={UserPage}/>
    </Switch>


function HeaderMenu(props) {
    if (props.isLogin) {
        return (
            <div className='head_menu'>
                <Dropdown overlay={LoginMenu} trigger={['click']}>
                    <a className="ant-dropdown-link" href="#">
                        {props.username} <Icon type="down"/>
                    </a>
                </Dropdown>
            </div>
        )
    } else {
        return (<div className="head_menu">null</div>)
    }
}


class UserPage extends Component {
    constructor(props) {
        super(props)
        console.log(this.props)

    }

    render() {
        return (<div>
            <h2>Userid: {this.props.match.params.userId}</h2>
        </div>)
    }
}


const LoginMenu = (
    <Menu>
        <Menu.Item key="0">
            <a href="/">个人资料</a>
        </Menu.Item>
        <Menu.Item key="1">
            <a href="http://www.taobao.com/">2nd menu item</a>
        </Menu.Item>
        <Menu.Divider/>
        <Menu.Item key="3"><a href="/logout">登出</a></Menu.Item>
    </Menu>
);


function GetMenuFromApi(props) {
    let menu
    if (props.isLogin) {
        menu = (<Menu theme="dark" mode="inline" defaultSelectedKeys={['999']}>
            <Menu.Item key='999'><Link to='/' exact={true}>主页</Link></Menu.Item>
            {

                Object.keys(props.menu.permissions).map((perm, index) => {
                    return (
                        <Menu.Item key={index}><Link
                            to={props.menu.permissions[perm].menu}
                            exact={index == 0 ? true : false}>{props.menu.permissions[perm].menu}</Link></Menu.Item>
                    )
                })
            }
        </Menu>)
    } else {
        menu = <div>没有登录</div>
    }

    return (
        <div>
            {menu}
        </div>
    )
}

class App extends Component {

    onCollapse = (collapsed) => {
        console.log(collapsed);
        this.setState({collapsed});
    }

    constructor(props) {
        super(props)
        this.state = {
            menu: {},
            collapsed: false,
            isLogin: false,
            username: null,
            routes: []
        }

    }

    componentWillMount() {
        axios.get('/get_permissions').then(res => {

            if (res.data.username == null) {
                this.setState({
                    menu: res.data,
                    isLogin: false
                })
            } else {
                let router = [
                    {
                        path: '/',
                        exact: true,
                        sidebar: () => <div>home</div>,
                        main: () => <Index/>
                    },
                ]

                Object.keys(res.data.permissions).map((menu_item, index) => {
                    router.push({
                        path: res.data.permissions[menu_item].menu,
                        exact: false,
                        main: () => <BaseList api={res.data.permissions[menu_item].api} columns={
                            Object.keys(res.data.permissions[menu_item].fields).map((field, index) => res.data.permissions[menu_item].fields[field])}
                            cols={res.data.permissions[menu_item].fields}
                        />
                    })
                })
                console.log(router)
                this.setState({
                    menu: res.data,
                    isLogin: true,
                    username: res.data.username,
                    routes: router,
                })
            }

            console.log(res.data)

        })
    }

    render() {
        return (
            <Router>
                <Layout style={{minHeight: '100vh'}}>
                    <Sider
                        breakpoint="lg"
                        collapsible
                        collapsed={this.state.collapsed}
                        onCollapse={this.onCollapse}
                    >
                        <div className="logo"/>
                        <GetMenuFromApi isLogin={this.state.isLogin} menu={this.state.menu}/>

                    </Sider>
                    <Layout>
                        <Header style={{background: '#fff', padding: 0}}>
                            <HeaderMenu isLogin={this.state.isLogin} username={this.state.username}
                                        style={{float: 'right'}}/>
                        </Header>
                        <Content style={{margin: '0 16px'}}>
                            <Breadcrumb style={{margin: '12px 0'}}>
                                {
                                    this.props.match &&
                                    this.props.match.url.splice("/").map((menu, index) => {
                                        return (<Breadcrumb.Item><Link to={`/${menu}`}>{menu}</Link></Breadcrumb.Item>)
                                    })

                                }
                            </Breadcrumb>

                            <div style={{padding: 24, background: '#fff', minHeight: 360}}>
                                {this.state.routes.map((route, index) => (
                                    // Render more <Route>s with the same paths as
                                    // above, but different components this time.
                                    <Route
                                        key={index}
                                        path={route.path}
                                        exact={route.exact}
                                        component={route.main}
                                    />
                                ))}
                                <Route path='/user' component={UserSubLayout}/>
                                <Route path='/list' component={ItemList}/>

                            </div>
                        </Content>
                        <Footer style={{textAlign: 'center'}}>
                            Ant Design ©2016 Created by Ant UED
                        </Footer>
                    </Layout>
                </Layout>
            </Router>
        );
    }
}


class Index extends Component {
    render() {
        return (<div>主页</div>)
    }
}


class UserList extends Component {
    constructor(props) {
        super(props);
        console.log(this.props);

        this.state = {
            pagination: {},
            loading: false,
            items: [],
            columns: [{
                title: '用户名',
                dataIndex: 'username',
                key: 'username',
                render: (username, record) => (<Link to={`/users/${record.id}`}> {username}</Link>)
            }, {
                title: '邮箱',
                dataIndex: 'email',
                key: 'email',
            }, {
                title: '是否是员工',
                dataIndex: 'is_staff',
                key: 'is_staff',
                render: is_staff => (is_staff ? '是' : '否')
            }, {
                title: 'url',
                dataIndex: 'url',
                key: 'url',
            }
            ]
        };
    }

    componentDidMount() {
        axios.get("/api/users/").then(res => {
            this.setState({
                items: res.data,
                loading: false
            })
        })
    }

    render() {
        return (
            <div>
                <Table dataSource={this.state.items} columns={this.state.columns} rowKey={record => record.registered}
                       loading={this.state.loading}/>
            </div>

        )
    }
}

class ItemList extends Component {

    handleTableChange = (pagination, filters, sorter) => {
        const pager = {...this.state.pagination};
        pager.current = pagination.current;
        this.setState({
            pagination: pager,
        });
        this.fetch({
            results: pagination.pageSize,
            page: pagination.current,
            sortField: sorter.field,
            sortOrder: sorter.order,
            ...filters,
        });
    }


    fetch = (params = {}) => {
        console.log('params:', params);
        this.setState({loading: true});

        axios.get(`https://api.guildwars2.com/v2/items`, {params: {page: params.page - 1}})
            .then(res => {
                const pagination = {...this.state.pagination};
                pagination.total = 1179 * 50;
                pagination.pageSize = 50;
                this.setState({
                    items: res.data,
                    // Read total count from server
                    // pagination.total = data.totalCount;
                    loading: false,
                    pagination,

                })
            });
    };

    constructor(props) {
        super(props);

        this.state = {
            pagination: {},
            loading: false,
            items: [],
            columns: [{
                title: '图标',
                dataIndex: 'icon',
                key: 'icon',
                render: img => <img src={img} alt="" className="img"/>
            }, {
                title: '名称',
                dataIndex: 'name',
                key: 'name',
                render: (name, record) => (<span className={record.rarity}>{name}</span>)
            }, {
                title: '描述',
                dataIndex: 'description',
                key: 'description',
            }, {
                title: '类型',
                dataIndex: 'type',
                key: 'type',
            }, {
                title: '品质',
                dataIndex: 'rarity',
                key: 'rarity',
            }, {
                title: '聊天代码',
                dataIndex: 'chat_link',
                key: 'chat_link',
            }
            ]
        };

    }

    componentDidMount() {
        this.fetch();
    }

    render() {
        return (
            <div>
                <Switch>
                    <Table dataSource={this.state.items} columns={this.state.columns}
                           rowKey={record => record.registered}
                           pagination={this.state.pagination}
                           loading={this.state.loading}
                           onChange={this.handleTableChange}
                    />
                </Switch>
            </div>

        )
    }
}

export default App;
